package com.tbynet.jwp.repository.impl;

import java.math.BigInteger;
import java.util.*;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core._JwpServiceProvider;
import com.tbynet.jwp.model.TermRelationships;
import com.tbynet.jwp.repository.spi.TermRelationshipService;

/**
 * 分类关系服务实现类 - 优化版（支持复合主键）
 * @ClassName: TermRelationshipServiceProvider
 * @Description: 负责分类关系数据的CRUD操作，支持复合主键表
 * @Author: 佰亿互联
 * @Date: 2025年11月4日
 *
 * @Copyright: 2025 www.tbynet.com Inc. All rights reserved.
 */
@Aop(TermRelationshipService.class)
public class TermRelationshipServiceImpl extends _JwpServiceProvider<TermRelationships> implements TermRelationshipService {

    // ========== 复合主键配置 ==========

    /** 复合主键字段名 */
    private static final String[] COMPOSITE_KEYS = {"object_id", "term_taxonomy_id"};

    /** 默认排序字段 */
    private static final String DEFAULT_ORDER_BY = "term_order ASC";

    // ========== 重写基类方法以支持复合主键 ==========

    /**
     * 获取复合主键字段名
     */
    protected String[] getCompositeKeys() {
        return COMPOSITE_KEYS;
    }

    /**
     * 获取实体ID方法 - 返回复合主键的Map
     */
    protected Object getEntityId(TermRelationships entity) {
        Map<String, Object> compositeKey = new HashMap<>();
        compositeKey.put(COMPOSITE_KEYS[0], entity.getObjectId());
        compositeKey.put(COMPOSITE_KEYS[1], entity.getTermTaxonomyId());
        return compositeKey;
    }

    @Override
    protected String buildSearchWhereSql(String keyword, List<Object> params) {
        return "";
    }

    /**
     * 重写默认排序
     */
    @Override
    protected String getDefaultOrderBy() {
        return DEFAULT_ORDER_BY;
    }

    // ========== 复合主键查询方法 ==========

    /**
     * 根据复合主键获取实体
     */
    public TermRelationships getByCompositeKey(Object objectId, Object termTaxonomyId) {
        if (objectId == null || termTaxonomyId == null) {
            log.debug("获取实体失败：复合主键参数为空");
            return null;
        }

        try {
            String sql = "SELECT * FROM " + getTableName() +
                    " WHERE object_id = ? AND term_taxonomy_id = ?";
            TermRelationships entity = getDao().findFirst(sql, objectId, termTaxonomyId);

            if (entity == null) {
                log.debug("未找到分类关系，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
            } else {
                log.debug("获取分类关系成功，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
            }
            return entity;

        } catch (Exception e) {
            log.error("根据复合主键获取实体失败，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId, e);
            return null;
        }
    }

    /**
     * 检查复合主键是否存在
     */
    public boolean existsByCompositeKey(Object objectId, Object termTaxonomyId) {
        if (objectId == null || termTaxonomyId == null) {
            return false;
        }

        try {
            String sql = "SELECT COUNT(*) FROM " + getTableName() +
                    " WHERE object_id = ? AND term_taxonomy_id = ?";
            Long count = Db.queryLong(sql, objectId, termTaxonomyId);
            return count != null && count > 0;

        } catch (Exception e) {
            log.error("检查复合主键存在性失败，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId, e);
            return false;
        }
    }

    // ========== 业务方法实现 ==========

    @Override
    public boolean saveTermRelationship(Object objectId, Object termTaxonomyId) {
        return saveTermRelationship(objectId, termTaxonomyId, 0);
    }

    @Override
    public boolean saveTermRelationship(Object objectId, Object termTaxonomyId, Integer termOrder) {
        if (objectId == null || termTaxonomyId == null) {
            log.warn("参数错误：objectId或termTaxonomyId为空");
            return false;
        }

        // 检查是否已存在
        if (existsByCompositeKey(objectId, termTaxonomyId)) {
            log.debug("分类关系已存在，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
            return updateTermOrder(objectId, termTaxonomyId, termOrder);
        }

        try {
            TermRelationships tr = new TermRelationships();
            tr.setObjectId(convertToBigInteger(objectId));
            tr.setTermTaxonomyId(convertToBigInteger(termTaxonomyId));
            tr.setTermOrder(termOrder != null ? termOrder : 0);

            boolean result = tr.save();
            if (result) {
                log.debug("保存分类关系成功，objectId: {}, termTaxonomyId: {}, termOrder: {}",
                        objectId, termTaxonomyId, termOrder);
            } else {
                log.warn("保存分类关系失败，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
            }
            return result;
        } catch (Exception e) {
            log.error("保存分类关系异常，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId, e);
            return false;
        }
    }

    @Override
    public boolean updateTermOrder(Object objectId, Object termTaxonomyId, Integer termOrder) {
        if (objectId == null || termTaxonomyId == null || termOrder == null) {
            log.warn("参数错误：objectId、termTaxonomyId或termOrder为空");
            return false;
        }

        try {
            String sql = "UPDATE " + getTableName() +
                    " SET term_order = ? WHERE object_id = ? AND term_taxonomy_id = ?";
            int result = Db.update(sql, termOrder, objectId, termTaxonomyId);

            if (result > 0) {
                log.debug("更新排序成功，objectId: {}, termTaxonomyId: {}, termOrder: {}",
                        objectId, termTaxonomyId, termOrder);
                return true;
            } else {
                log.warn("更新排序失败，未找到对应记录，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
                return false;
            }
        } catch (Exception e) {
            log.error("更新排序异常，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId, e);
            return false;
        }
    }

    @Override
    public boolean deletePostTermRelationships(Object objectId, String taxonomy) {
        if (objectId == null || StrKit.isBlank(taxonomy)) {
            log.warn("参数错误：objectId或taxonomy为空");
            return false;
        }

        try {
            String sql = "DELETE tr FROM " + getTableName() + " tr " +
                    "INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id " +
                    "WHERE tr.object_id = ? AND tt.taxonomy = ?";
            int result = Db.update(sql, objectId, taxonomy);

            log.info("删除分类关系完成，objectId: {}, taxonomy: {}, 影响行数: {}", objectId, taxonomy, result);
            return result >= 0;
        } catch (Exception e) {
            log.error("删除分类关系异常，objectId: {}, taxonomy: {}", objectId, taxonomy, e);
            return false;
        }
    }

    @Override
    public boolean deleteByCompositeKey(Object objectId, Object termTaxonomyId) {
        if (objectId == null || termTaxonomyId == null) {
            log.warn("参数错误：objectId或termTaxonomyId为空");
            return false;
        }

        try {
            String sql = "DELETE FROM " + getTableName() +
                    " WHERE object_id = ? AND term_taxonomy_id = ?";
            int result = Db.update(sql, objectId, termTaxonomyId);

            if (result > 0) {
                log.debug("删除分类关系成功，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
                return true;
            } else {
                log.warn("删除分类关系失败，未找到对应记录，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId);
                return false;
            }
        } catch (Exception e) {
            log.error("删除分类关系异常，objectId: {}, termTaxonomyId: {}", objectId, termTaxonomyId, e);
            return false;
        }
    }

    // ========== 批量操作方法 ==========

    /**
     * 批量保存分类关系
     */
    public int batchSaveTermRelationships(List<Map<String, Object>> relationships) {
        if (relationships == null || relationships.isEmpty()) {
            log.debug("批量保存分类关系：关系列表为空");
            return 0;
        }

        int successCount = 0;
        for (Map<String, Object> relation : relationships) {
            Object objectId = relation.get("objectId");
            Object termTaxonomyId = relation.get("termTaxonomyId");
            Integer termOrder = (Integer) relation.get("termOrder");

            if (objectId != null && termTaxonomyId != null) {
                if (saveTermRelationship(objectId, termTaxonomyId, termOrder)) {
                    successCount++;
                }
            }
        }

        log.info("批量保存分类关系完成，总数: {}, 成功: {}", relationships.size(), successCount);
        return successCount;
    }

    /**
     * 根据对象ID批量删除分类关系
     */
    public int batchDeleteByObjectId(Object objectId) {
        if (objectId == null) {
            log.warn("参数错误：objectId为空");
            return 0;
        }

        try {
            String sql = "DELETE FROM " + getTableName() + " WHERE object_id = ?";
            int result = Db.update(sql, objectId);

            log.info("根据对象ID批量删除分类关系完成，objectId: {}, 影响行数: {}", objectId, result);
            return result;
        } catch (Exception e) {
            log.error("根据对象ID批量删除分类关系异常，objectId: {}", objectId, e);
            return 0;
        }
    }

    // ========== 查询方法 ==========

    /**
     * 根据对象ID获取分类关系列表
     */
    public List<TermRelationships> getByObjectId(Object objectId) {
        if (objectId == null) {
            log.debug("参数错误：objectId为空");
            return new ArrayList<>();
        }

        try {
            String sql = "SELECT * FROM " + getTableName() +
                    " WHERE object_id = ? ORDER BY " + getDefaultOrderBy();
            List<TermRelationships> result = getDao().find(sql, objectId);

            log.debug("根据对象ID获取分类关系完成，objectId: {}, 数量: {}", objectId, result.size());
            return result;
        } catch (Exception e) {
            log.error("根据对象ID获取分类关系失败，objectId: {}", objectId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据分类ID获取分类关系列表
     */
    public List<TermRelationships> getByTermTaxonomyId(Object termTaxonomyId) {
        if (termTaxonomyId == null) {
            log.debug("参数错误：termTaxonomyId为空");
            return new ArrayList<>();
        }

        try {
            String sql = "SELECT * FROM " + getTableName() +
                    " WHERE term_taxonomy_id = ? ORDER BY " + getDefaultOrderBy();
            List<TermRelationships> result = getDao().find(sql, termTaxonomyId);

            log.debug("根据分类ID获取分类关系完成，termTaxonomyId: {}, 数量: {}", termTaxonomyId, result.size());
            return result;
        } catch (Exception e) {
            log.error("根据分类ID获取分类关系失败，termTaxonomyId: {}", termTaxonomyId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取对象的分类ID列表
     */
    public List<BigInteger> getTermTaxonomyIdsByObjectId(Object objectId) {
        if (objectId == null) {
            return new ArrayList<>();
        }

        try {
            String sql = "SELECT term_taxonomy_id FROM " + getTableName() +
                    " WHERE object_id = ? ORDER BY term_order ASC";
            List<Record> records = Db.find(sql, objectId);

            List<BigInteger> result = new ArrayList<>();
            for (Record record : records) {
                result.add(record.getBigInteger("term_taxonomy_id"));
            }

            log.debug("获取对象分类ID列表完成，objectId: {}, 数量: {}", objectId, result.size());
            return result;
        } catch (Exception e) {
            log.error("获取对象分类ID列表失败，objectId: {}", objectId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 统计分类的使用次数
     */
    public long countByTermTaxonomyId(Object termTaxonomyId) {
        if (termTaxonomyId == null) {
            return 0;
        }

        try {
            String sql = "SELECT COUNT(*) FROM " + getTableName() + " WHERE term_taxonomy_id = ?";
            Long count = Db.queryLong(sql, termTaxonomyId);
            return count != null ? count : 0;
        } catch (Exception e) {
            log.error("统计分类使用次数失败，termTaxonomyId: {}", termTaxonomyId, e);
            return 0;
        }
    }

    // ========== 工具方法 ==========

    /**
     * 转换为BigInteger
     */
    private BigInteger convertToBigInteger(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof BigInteger) {
            return (BigInteger) value;
        }
        if (value instanceof Number) {
            return BigInteger.valueOf(((Number) value).longValue());
        }
        return new BigInteger(value.toString());
    }

    /**
     * 构建复合主键查询SQL
     */
    private String buildCompositeKeySql() {
        return "object_id = ? AND term_taxonomy_id = ?";
    }
}